package com.mall.order.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.order.CancelOrderService;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CancelOrderRequest;
import com.mall.order.dto.CancelOrderResponse;
import com.mall.shopping.constants.ShoppingRetCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Slf4j
@Component
@Service
public class CancelOrderServiceImpl implements CancelOrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();
        try {
            request.requestCheck();
        } catch (ValidateException e) {
            response.setCode(e.getErrorCode());
            response.setMsg(e.getMessage());
            return response;
        }
        String orderId = request.getOrderId();

        //改变订单状态
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
        int cancel = orderMapper.updateByPrimaryKeySelective(order);

        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId",orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        int cancelOrder = 0;
        for (OrderItem orderItem : orderItems) {
            Stock cancelStock = new Stock();
            cancelStock.setItemId(orderItem.getItemId());
            cancelStock.setStockCount(Long.valueOf(orderItem.getNum()));
            cancelStock.setLockCount(-orderItem.getNum());
            cancelOrder += stockMapper.updateStockCancelOrder(cancelStock);
        }


        if (cancel != 1 || cancelOrder < 1) {
            response.setCode(ShoppingRetCode.DB_EXCEPTION.getCode());
            response.setMsg(ShoppingRetCode.DB_EXCEPTION.getMessage());
            return response;
        }
        response.setCode(ShoppingRetCode.SUCCESS.getCode());
        response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        return response;
    }
}
